# 定义一个File类
class File:
    def __init__(self, file_name, file_model, encoding):
        self.file_name = file_name
        self.file_model = file_model
        self.encoding = encoding

    # 实现__enter__()和__exit__()方法
    def __enter__(self):
        print("这是上文")
        self.file = open(self.file_name, self.file_model, encoding=self.encoding)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("这是下文")
        self.file.close()


# 使用with语句来完成文件操作
with File("test.txt", "w", 'utf-8') as f:
    f.write("hello world")

